package com.se.controller;

import cn.hutool.crypto.asymmetric.RSA;
import com.se.enums.ResultCode;
import com.se.domain.vo.ResultVO;
import com.se.exception.ResultException;
import com.se.global.AuthHeaderRequestWrapper;
import com.se.service.AuthService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.concurrent.TimeUnit;

@RestController
public class AuthController {
    @Autowired
    AuthService authService;
    @Autowired
    private StringRedisTemplate redisTemplate;

    @PostMapping("/no/auth/login/test")
    public ResultVO<Long> loginTest(
            @RequestParam Long userId,
            HttpSession session) throws ResultException {
        userId = authService.loginTest(userId);
        if(userId == null){
            throw new ResultException(ResultCode.FAIL.getCode(), "不存在该用户");
        }
        this.userLogin(session, userId);
        return ResultVO.ok(userId);
    }
    @PostMapping("/no/auth/login/code")
    public ResultVO<Long> loginByCode(
            @RequestParam String code,
            HttpSession session
    ) throws ResultException {
        Long userId = authService.loginByCode(code);
        this.userLogin(session, userId);
        return ResultVO.ok(userId);
    }

    @PostMapping("/need/auth/login/check")
    public ResultVO<Long> checkLogin(
            @RequestHeader(value = AuthHeaderRequestWrapper.USER_ID_HEADER_NAME, required = false) Long userId
    ) throws ResultException {
        return ResultVO.ok(userId);
    }

    @PostMapping("/must/auth/key")
    public ResultVO<String> generateKey(
            @RequestHeader(value = AuthHeaderRequestWrapper.USER_ID_HEADER_NAME, required = false) Long userId,
            HttpSession session
    ) throws ResultException {
        RSA rsa = new RSA();
        redisTemplate.opsForValue().set(userId+"-privateKey", rsa.getPrivateKeyBase64());
        redisTemplate.expire(userId+"-privateKey", 5, TimeUnit.MINUTES);

        return ResultVO.ok(rsa.getPublicKeyBase64());
    }

    @Value("${auth.user-token.name}")
    String userTokenName;
    private void userLogin(HttpSession session, Long userId){
        if(userId == null){
            return;
        }
        String userToken = authService.generateAndStoreUserToken(userId);
        session.setAttribute(this.userTokenName, userToken);
        session.setMaxInactiveInterval(-1);
    }
}
